package com.yql.biz.core.filter;

import com.yql.common.config.RuoYiConfig;
import com.yql.common.json.JSON;
import com.yql.commonextend.response.CommonResponse;
import com.yql.commonextend.response.ResponseConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Version 1.0
 * @Author: fengtianhe
 * @Date: 2021/6/28
 * Content: 开放页面鉴权校验
 */
@Component
@WebFilter(urlPatterns = "/**", filterName = "ParameterRequestFilter", dispatcherTypes = DispatcherType.REQUEST)
public class ParameterRequestFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(ParameterRequestFilter.class);

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        if (RuoYiConfig.getCrypticSwitch()){
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String path = request.getRequestURI();
            if (path.startsWith("/app/pay/topUpCallback") || path.startsWith("/app/pay/callback")) {
                filterChain.doFilter(request, servletResponse);
            } else {
                ParameterRequestWrapper requestWrapper = null;
                try {
                    requestWrapper = new ParameterRequestWrapper(request);
                }catch (Exception e){
                    log.error("ParameterRequestFilter通用解密失败：",e);
                    //解密失败，返回非法操作
                    CommonResponse resp = CommonResponse.RespWithCodeMsg(ResponseConstant.RESP_ERROR_CODE, ResponseConstant.RESP_ERROR_MESG);
                    try {
                        this.renderString(servletResponse, JSON.marshal(resp));
                    }catch (Exception e1){
                        log.error("JSON.marshal异常:", e1);
                    }
                }
                filterChain.doFilter(requestWrapper, servletResponse);
            }
        }else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    private void renderString(ServletResponse response, String responseString) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            out = response.getWriter();
            out.print(responseString);
        }catch (IOException e){
            log.error("IOException异常", e);
        }finally {
            out.flush();
            out.close();
        }
    }

    @Override
    public void destroy() {
    }

}
